rebol [
title: "bean helpers" file: %bean-funcs.r
comment: "inbuild in %bean-templates.r"
]

top-array: func [blk] [
    blk/b/java/b/array
]

beans-to-rebol: func [bean-arr /local out len] [
    out: copy []
    len: load bean-arr/a/length
    insert/dup out: copy [] 'unknown len
    expand-bean-ids bean-arr/b
    foreach entry bean-arr/b [
        if block? entry [
            ix: 1 + load entry/a/index
            out/:ix: bean-to-val entry/b/3
        ]
    ]
    new-line/all out true
    out
]

rebol-to-beans: func [blk /local out] [
    out: copy []
    foreach val blk [
        append out val-to-bean :val ;lit-word needs :val
    ]
    out
]

;hack für array of bytes for tuple
byte!: :integer!

to-bean-entry: func [blk-at /local entry] [
    entry: copy/deep bean-result-entry
    insert/part entry/void/b blk-at 2
    entry/void/a/index: mold (index? blk-at) - 1 / 2
    entry
]

to-bean-result: func [blk /local res] [
    res: copy/deep bean-result-template
    res/java/b/array/a/length: mold (length? blk) / 2
    forskip blk 2 [
        append res/java/b/array/b to-bean-entry blk
    ]
    res
]

to-bean-array: func[blk /local res][
    res: to-bean-result rebol-to-beans blk
    res: res/java/b/array
]

to-bean-tuple: func[blk /local res][
???
res: to-bean-array blk
res/a/class: "byte"
foreach val probe by-mark res/b 'void[
 val/b/int/1: "byte"
]
??
res
]

expand-bean-ids: func[xml-body /local ids p id rule tag break?][
 ids: copy[]
 parse xml-body rule: [
 		any[
 			into [
 				tag: string!
 	'a p: [
 	block! (
 		if id: select p/1 'id [
 			repend ids [id tag]
 		]
 		;break-hack..
 		break?: either id: select p/1 'idref[
 			orig: select ids id
 			tag/a: orig/a
 			tag/b: orig/b
 			'break
 		][
 			[]
 		]
 	) break? | skip
 	]
 	'b into rule
 			] | skip
 		]
 
 ]
 xml-body
]

index-by-path: func[blk path /local out][
	out: copy[]
	foreach item blk[
		path/1: 'item ;bound right
		repend out[ attempt[do path] item ]
	]
	out
]

by-path: func[blk path /local out][
	out: copy[]
	foreach item blk[
		path/1: 'item ;bound right
		if key: attempt[do path] [
			repend out[ key item ]
		]
	]
	out
]

by-mark: func[blk type /local out][
	out: copy[]
	while[blk: find blk type][
		repend out [blk/2]
		blk: skip blk 2
	]
	out
]

get-property: func[val name][
	val: by-path by-mark val 'void 'item/a/property 
	val: select val name
]

get-bean-string: func[val][
	 val: get-property val "string" 
	 val/b/string/b/1
]

set-bean-string: func[val name][
	 val: get-property val "string" 
	 val/b/string/b/1: name
]

bean-0date: 1-jan-1970/0:0+0:0

to-reb-date: func[val][
	val: copy val
	insert skip tail val -3 "."
	val: to-time to-decimal val
	val: bean-0date + val + now/zone
	val/zone: now/zone
	val
]

to-bean-date: func[target val][	
	val: form to-money to-decimal 1000 * difference val bean-0date ; to-money hack to get around "e"
	clear find val "."	
	val
]

